package com.ruoyi.web.controller.translation;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import okhttp3.*;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.concurrent.TimeUnit;

/**
 * @Title: 归属 secret_id secret_key
 * @author: WYJ
 * @date: 2025/10/9
 */
public class TencentTranslationHttp {

    private static final String SECRET_ID = "AKIDGOJ1VmHfqpfOvGQNpEYjhSzINFtJYfcL";
    private static final String SECRET_KEY = "bzA9QYVGn6D6lCQTLzPeiYAZlmaBbonZ";
    private static final String ENDPOINT = "tmt.tencentcloudapi.com";
    private static final String ACTION = "TextTranslate";
    private static final String VERSION = "2018-03-21";
    private static final String REGION = "ap-shanghai";

    private OkHttpClient client;
    private ObjectMapper objectMapper;

    public TencentTranslationHttp() {
        this.client = new OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS)
                .readTimeout(10, TimeUnit.SECONDS)
                .build();
        this.objectMapper = new ObjectMapper();
    }

    public String translate(String sourceText, String sourceLang, String targetLang)
            throws IOException, NoSuchAlgorithmException, InvalidKeyException {

        // 构造请求参数
        String payload = String.format(
                "{\"SourceText\":\"%s\",\"Source\":\"%s\",\"Target\":\"%s\",\"ProjectId\":0}",
                sourceText, sourceLang, targetLang
        );

        // 生成签名
        String authorization = generateSignature(payload);

        // 构造请求
        Request request = new Request.Builder()
                .url("https://" + ENDPOINT)
                .post(RequestBody.create(payload, MediaType.parse("application/json")))
                .addHeader("Authorization", authorization)
                .addHeader("X-TC-Action", ACTION)
                .addHeader("X-TC-Version", VERSION)
                .addHeader("X-TC-Timestamp", String.valueOf(System.currentTimeMillis() / 1000))
                .addHeader("X-TC-Region", REGION)
                .build();

        // 发送请求
        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("请求失败: " + response);
            }

            String responseBody = response.body().string();
            JsonNode root = objectMapper.readTree(responseBody);
            return root.path("Response").path("TargetText").asText();
        }
    }

    private String generateSignature(String payload) throws NoSuchAlgorithmException, InvalidKeyException {
        String service = "tmt";
        String timestamp = String.valueOf(System.currentTimeMillis() / 1000);
        String date = timestamp.substring(0, 8);

        // 构造签名字符串
        String canonicalRequest = "POST\n/\n\n" +
                "content-type:application/json\n" +
                "host:" + ENDPOINT + "\n" +
                "\n" +
                "content-type;host\n" +
                sha256Hex(payload);

        String stringToSign = "TC3-HMAC-SHA256\n" +
                timestamp + "\n" +
                date + "/" + service + "/tc3_request\n" +
                sha256Hex(canonicalRequest);

        // 计算签名
        byte[] secretDate = hmac256(("TC3" + SECRET_KEY).getBytes(StandardCharsets.UTF_8), date);
        byte[] secretService = hmac256(secretDate, service);
        byte[] secretSigning = hmac256(secretService, "tc3_request");
        byte[] signature = hmac256(secretSigning, stringToSign);

        return "TC3-HMAC-SHA256 " +
                "Credential=" + SECRET_ID + "/" + date + "/" + service + "/tc3_request, " +
                "SignedHeaders=content-type;host, " +
                "Signature=" + bytesToHex(signature);
    }

    private String sha256Hex(String s) throws NoSuchAlgorithmException {
        java.security.MessageDigest md = java.security.MessageDigest.getInstance("SHA-256");
        byte[] digest = md.digest(s.getBytes(StandardCharsets.UTF_8));
        return bytesToHex(digest);
    }

    private byte[] hmac256(byte[] key, String msg) throws NoSuchAlgorithmException, InvalidKeyException {
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(new SecretKeySpec(key, "HmacSHA256"));
        return mac.doFinal(msg.getBytes(StandardCharsets.UTF_8));
    }

    private String bytesToHex(byte[] bytes) {
        StringBuilder result = new StringBuilder();
        for (byte b : bytes) {
            result.append(String.format("%02x", b));
        }
        return result.toString();
    }
}
